package sort.ui.gwt.server;

import sort.algorithm.Sorter;
import sort.record.Records;
import sort.result.SortResult;
import sort.result.SortResultWatcher;
import sort.ui.gwt.client.SortService;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class SortServiceImpl extends RemoteServiceServlet implements SortService {

	@Override
	public SortResult sortServer(Records records,String algorithmClassName) throws IllegalArgumentException {
		Sorter sorter;
		try {
			sorter = (Sorter)Class.forName(algorithmClassName).newInstance();
		} catch ( ClassNotFoundException e) {
			throw new IllegalArgumentException("Class Not Found "+algorithmClassName ,e.fillInStackTrace());
		} catch (InstantiationException e) {
			throw new IllegalArgumentException("Can't Instantiation "+algorithmClassName ,e.fillInStackTrace());
		} catch (IllegalAccessException e) {
			throw new IllegalArgumentException("Illegal Access "+algorithmClassName ,e.fillInStackTrace());
		}
		SortResultWatcher watcher = new SortResultWatcher(sorter.getName());

		watcher.start(records);
		Records sorted = sorter.sort(records.copy());
		watcher.finish(sorted);
		SortResult result = watcher.getResult();
		
//		HttpSession session = getThreadLocalRequest().getSession();
//		String cookievalue = (String)session.getAttribute("test01");
//		if ( cookievalue == null ) {
//			session.setAttribute("test01", "testtest");
//		}
		
		return result;
	}
}
